package com.tqz.rc.spring.cloud.registry;

import com.tqz.rc.api.Instance;
import com.tqz.rc.client.naming.NamingService;
import com.tqz.rc.spring.cloud.TqzRcProperties;
import com.tqz.rc.spring.cloud.TqzRcServiceManager;
import org.springframework.cloud.client.serviceregistry.Registration;
import org.springframework.cloud.client.serviceregistry.ServiceRegistry;
import org.springframework.context.annotation.Configuration;

/**
 * <p>实现spring-cloud-common的规范进行服务注册。
 *
 * @author tianqingzhao
 * @since 2021/9/2 14:35
 */
@Configuration
public class TqzRcServiceRegistry implements ServiceRegistry<Registration> {

    private final TqzRcProperties tqzRcProperties;

    private final TqzRcServiceManager tqzRcServiceManager;

    public TqzRcServiceRegistry(TqzRcProperties tqzRcProperties, TqzRcServiceManager tqzRcServiceManager) {
        this.tqzRcProperties = tqzRcProperties;
        this.tqzRcServiceManager = tqzRcServiceManager;
    }

    @Override
    public void register(Registration registration) {

        String serviceId = registration.getServiceId();
        String groupName = tqzRcProperties.getGroupName();

        Instance instance = getNacosInstanceFromRegistration(registration);

        try {
            // 进入到调用nacos客户端api
            getNamingService().registerInstance(serviceId, groupName, instance);
            System.out.println("服务 " + serviceId + "，组名：" + groupName +
                    "，ip：" + instance.getIp() + "，端口号：" + instance.getPort() + " 注册完成。");
        } catch (Exception e) {
            throw new RuntimeException("注册服务失败。");
        }
    }

    @Override
    public void deregister(Registration registration) {
        System.out.println("注销服务。");
    }

    @Override
    public void close() {
        System.out.println("关闭服务。");
        tqzRcServiceManager.tqzRcServiceShutdown();
    }

    @Override
    public void setStatus(Registration registration, String status) {
        System.out.println("设置服务的状态。");
    }

    @Override
    public <T> T getStatus(Registration registration) {
        return (T) "UP";
    }

    private NamingService getNamingService() {
        return tqzRcServiceManager.getNamingService(tqzRcProperties.getTqzRcProperties());
    }

    private Instance getNacosInstanceFromRegistration(Registration registration) {
        Instance instance = new Instance();
        instance.setIp(registration.getHost());
        instance.setPort(registration.getPort());
        instance.setNamespaceId(tqzRcProperties.getNamespaceId());
        instance.setClusterName(tqzRcProperties.getClusterName());
        instance.setMetadata(registration.getMetadata());
        instance.setEphemeral(tqzRcProperties.isEphemeral());
        return instance;
    }
}
